<template>
	<div class="box">
		<div class="title">合同</div>
		<div class="">
			<div class="container_title">
				<FormItems
					ref="form"
					v-model="formData.leaseContract"
					:form="formList"
					:state="state"
					labelWidth="120px"></FormItems>
			</div>
			<div class="container_content" v-loading="loading">
				<other-effective-template
					ref="contractFrom"
					v-if="
						formData.leaseContract.contractTemplateSchemeType == 2
					"
					@getContractContent="handleSeeContractContent"
					:customer-id="details.leaseeId"
					:planID="details.schemeId"
					:newOrOldCars="details.carType"
					:customerTypeCode="details.customerTypeCode"
					:state="state"
					:type="type"
					@downTemplate="downTemplate"></other-effective-template>
				<customer-company-template
					ref="contractFrom"
					v-else-if="
						formData.leaseContract.contractTemplateSchemeType ==
							3 ||
						formData.leaseContract.contractTemplateSchemeType == 4
					"
					:applicationType="
						formData.leaseContract.contractTemplateSchemeType * 1
					"
					@getContractContent="handleSeeContractContent"
					:customer-id="details.leaseeId"
					:planID="details.schemeId"
					:newOrOldCars="details.carType"
					:customerTypeCode="details.customerTypeCode"
					:state="state"
					:type="type"
					@downTemplate="downTemplate"></customer-company-template>
				<enable-invalid-template
					ref="contractFrom"
					v-else-if="
						formData.leaseContract.contractTemplateSchemeType == 5
					"
					@getContractContent="handleSeeContractContent"
					:customer-id="details.leaseeId"
					:planID="details.schemeId"
					:newOrOldCars="details.carType"
					:customerTypeCode="details.customerTypeCode"
					:state="state"
					:type="type"
					@downTemplate="downTemplate"></enable-invalid-template>
			</div>
			<div>
				<el-form
					:model="formData"
					ref="form"
					label-width="120px"
					:inline="false"
					size="normal">
					<el-form-item
						label="买卖合同模板"
						v-if="formData.rentType_raw == '2'"
						prop="salesContract"
						:rules="salesContractRules">
						<el-select
							v-model="salesContract"
							value-key="id"
							placeholder=""
							clearable
							filterable
							size="small"
							@change="change('salesContract')"
							v-loading="loading"
							:disabled="state == 'readonly'">
							<el-option
								v-for="item in salesContractList"
								:key="item.id"
								:label="item.templateName"
								:value="item"></el-option>
						</el-select>
						<el-button
							size="small"
							v-show="notEmpty(salesContract)"
							style="margin-left: 15px"
							type="text"
							@click="handleSeeContractContent(salesContract.id)">
							查看
						</el-button>
						<el-button
							type="text"
							v-if="
								salesContract &&
								salesContract.id &&
								type == 'preview'
							"
							@click="downTemplate(salesContract.id)">
							下载
						</el-button>
					</el-form-item>
					<el-form-item
						label="担保合同模板"
						:rules="guaranteeContractRules"
						prop="guaranteeContract">
						<el-select
							size="small"
							v-model="guaranteeContract"
							value-key="id"
							placeholder=""
							clearable
							filterable
							@change="change('guaranteeContract')"
							v-loading="loading"
							:disabled="state == 'readonly'">
							<el-option
								v-for="item in guaranteeContractList"
								:key="item.id"
								:label="item.templateName"
								:value="item"></el-option>
						</el-select>
						<el-button
							v-show="notEmpty(guaranteeContract)"
							style="margin-left: 15px"
							type="text"
							size="small"
							@click="
								handleSeeContractContent(guaranteeContract.id)
							">
							查看
						</el-button>
						<el-button
							type="text"
							v-if="
								guaranteeContract &&
								guaranteeContract.id &&
								type == 'preview'
							"
							@click="downTemplate(guaranteeContract.id)">
							下载
						</el-button>
					</el-form-item>
				</el-form>
			</div>
		</div>
		<common-contract-content
			ref="commonContractContent"></common-contract-content>
	</div>
</template>

<script>
	import preview from '@/components/A/previewDialog/preview.js';
	import FormItems from '@/views/finance/manage/formItems/index.vue';
	import FormItem from '@/views/finance/reimburs/formItem/index.vue';
	import ContractTemplateUpload from '@/components/FileUpload/contractTemplateUpload.vue';

	import OtherEffectiveTemplate from './template/changeTypeForms/OtherEffectiveTemplate.vue';
	// import CustomerCompanyTemplate from "@/views/contractTemplate/components/changeTypeForms/CustomerCompanyTemplate.vue";
	// import EnableInvalidTemplate from "@/views/contractTemplate/components/changeTypeForms/EnableInvalidTemplate.vue";
	import CustomerCompanyTemplate from './template/changeTypeForms/CustomerCompanyTemplate.vue';
	import EnableInvalidTemplate from './template/changeTypeForms/EnableInvalidTemplate.vue';
	import CommonContractContent from '@/views/contractTemplate/components/CommonContractContent.vue';
	import * as app from '@/api/app.js';
	export default {
		components: {
			FormItems,
			FormItem,
			ContractTemplateUpload,
			OtherEffectiveTemplate,
			CustomerCompanyTemplate,
			EnableInvalidTemplate,
			CommonContractContent,
		},
		props: {
			value: {
				required: false,
			},
			state: {
				required: false,
			},
			type: {
				required: false,
			},
		},
		data() {
			return {
				loading: false,
				salesContract: {}, //买卖合同模板
				guaranteeContract: {}, //担保合同模板
				salesContractList: [], //买卖合同模板
				guaranteeContractList: [], //担保合同模板
			};
		},
		dicts: ['contract_template_edit_type'],
		inject: ['details_forecast', '_from', 'details_config'],
		computed: {
			salesContractRules() {
				if (this._from == 'apply') {
					return [
						{
							required: true,
							trigger: 'change',
							validator: (_1, _2, callback) => {
								if (
									this._from == 'apply' &&
									this.notEmpty(this.salesContract)
								) {
									callback();
								} else {
									callback(new Error('请选择买卖合同模板'));
								}
							},
						},
					];
				} else {
					return [];
				}
			},
			config() {
				let config = this.details_config();
				return config;
			},
			guaranteeContractRules() {
				if (this._from == 'apply') {
					if (this.details.sourceBusinessType == '2') {
						return [
							{
								required: true,
								trigger: 'change',
								validator: (_1, _2, callback) => {
									if (
										this._from == 'apply' &&
										this.notEmpty(this.guaranteeContract)
									) {
										callback();
									} else {
										callback(
											new Error('请选择担保合同模板'),
										);
									}
								},
							},
						];
					} else {
						return [];
					}
				} else {
					return [];
				}
			},
			details() {
				return this.details_forecast();
			},
			formData: {
				get() {
					return this.useVModel.call(this);
				},
				set(val) {
					this.$emit('input', val);
				},
			},

			contract_template_edit_type() {
				return this.dict?.type?.contract_template_edit_type?.filter(
					item => item.value != 1,
				);
			},
			formList() {
				return [
					{
						label: '合同模板方案',
						type: 'radioGroup',
						radioGroupList: this.contract_template_edit_type,
						prop: 'contractTemplateSchemeType',
						rules: this._from == 'apply' ? true : false,
						block: true,
						event: {
							type: 'change',
							cb: row => {
								this.$refs.contractFrom?.initForm?.();
								// this.initLeaseContract();
							},
						},
					},
				];
			},
		},

		created() {
			this.init();
		},
		mounted() {
			this.formData.leaseContract.contractTemplateSchemeType ||= '2';
			this.$emitter.on('getTemplateList', this.getTemplateList);
		},

		methods: {
			downTemplate(contractTemplateId) {
				if (this.notEmpty(contractTemplateId)) {
					this.$download.contractTemplate(contractTemplateId);
				} else {
					this.$message.error('模版id为空,无法下载');
				}
			},
			valid() {
				return new Promise(async resolve => {
					let result = true;
					let refs = Object.values(this.$refs);
					for (let index = 0; index < refs?.length; index++) {
						const ref = refs[index];
						if (
							Object.prototype.toString.call(ref) ==
							'[object Array]'
						) {
							for (let i = 0; i < ref.length; i++) {
								const element = ref[i];
								if (element?.valid) {
									let rc = await element?.valid?.();
									result = result && rc;
								}
								if (element?.validate) {
									let rf = await this._valid(ref);
									result = result && rf;
								}
								if (element?.form_validate) {
									let rf = await this._valid(
										ref,
										'form_validate',
									);
									result = result && rf;
								}
							}
						} else {
							if (ref?.valid) {
								let rc = await ref?.valid?.();
								result = result && rc;
							}
							if (ref?.validate) {
								let rf = await this._valid(ref);
								result = result && rf;
							}
							if (ref?.form_validate) {
								let rf = await this._valid(
									ref,
									'form_validate',
								);
								result = result && rf;
							}
						}
					}
					resolve(result);
				});
			},
			initLeaseContract() {
				this.formData.leaseContract.contractTemplateId = '';
				this.formData.leaseContract.contractTemplateCode = '';
				this.formData.leaseContract.contractTemplateName = '';
				this.formData.leaseContract.snapshootData = '';
			},
			async handleSeeContractContent(id) {
				if (!this.isNull(id)) {
					this.$refs.commonContractContent.show(id);
					// let data = await this.$download.contractTemplateRawdata(id);
					// if (data) {
					// 	let url = URL.createObjectURL(data);
					// 	preview({
					// 		url: {
					// 			url,
					// 			type: 'docx',
					// 		},
					// 	});
					// }
				} else {
					this.$message.error('模版id为空,无法查看');
				}
			},
			change(type) {
				if (type == 'salesContract') {
					this.formData.salesContract ??= {};
					this.formData.salesContract.contractTemplateType = '2'; // 合同模板类型 固定
					this.formData.salesContract.contractTemplateSchemeType =
						this.formData.leaseContract.contractTemplateSchemeType;
					this.formData.salesContract.contractTemplateId =
						this[type].id;
					this.formData.salesContract.contractTemplateCode =
						this[type].templateCode;
					this.formData.salesContract.contractTemplateName =
						this[type].templateName;
					if (!this?.salesContract?.templateCode) {
						this.formData.salesContract = null;
					}
				} else if (type == 'guaranteeContract') {
					this.formData.guaranteeContract ??= {};
					this.formData.guaranteeContract.contractTemplateType = '3'; // 合同模板类型 固定
					this.formData.guaranteeContract.contractTemplateSchemeType =
						this.formData.leaseContract.contractTemplateSchemeType;
					this.formData.guaranteeContract.contractTemplateId =
						this[type].id;
					this.formData.guaranteeContract.contractTemplateCode =
						this[type].templateCode;
					this.formData.guaranteeContract.contractTemplateName =
						this[type].templateName;
					if (!this?.guaranteeContract?.templateCode) {
						this.formData.guaranteeContract = null;
					}
				}
				this.$emit('input', this.formData);
			},
			async init() {
				// await this.getContractList("1");
				// await this.getContractList("2");
				this.loading = true;
				await Promise.all([
					this.getContractList('1'),
					this.getContractList('2'),
				]);
				this.setFormData();
				this.loading = false;
			},
			getTemplateList() {
				this.guaranteeContract = {};
				this.formData.guaranteeContract = null;
				this.salesContract = {};
				this.formData.salesContract = null;
				this.getContractList('1');
				this.getContractList('2');
			},
			getContractList(templateClassification) {
				return new Promise((resolve, reject) => {
					let params = {
						templateClassification,
						relatedCustomers: this.details.leaseeId,
					};
					app.TemplateList(params)
						.then(res => {
							if (res.code == 200) {
								if (templateClassification == '1') {
									this.salesContractList = res.data;
								}
								if (templateClassification == '2') {
									this.guaranteeContractList = res.data;
								}
							}
						})
						.finally(() => resolve());
				});
			},
			getFormData(type) {
				let form = this.$refs.contractFrom.saveForm(type);
				if (this.notEmpty(form)) {
					return form;
				} else {
					return null;
				}
			},
			getForm() {
				return this.$refs.contractFrom.getForm();
			},
			setFormData() {
				this.$nextTick(() => {
					try {
						// 租赁合同模板
						if (this.notEmpty(this.formData?.leaseContract)) {
							if (
								this.formData?.leaseContract
									.contractTemplateSchemeType == '2'
							) {
								this.$refs.contractFrom.form.newTemplateObj =
									this.formData?.leaseContract;
								this.$nextTick(() => {
									this.$refs.contractFrom?.form1_clearValidate?.();
								});
							} else if (
								this.formData?.leaseContract
									.contractTemplateSchemeType !== '' &&
								this.formData?.leaseContract?.snapshootData
							) {
								let data = JSON.parse(
									this.Base64.decode(
										this.formData?.leaseContract
											?.snapshootData,
									),
								);
								if (data?.contractTemplate) {
									this.$refs.contractFrom.form =
										data?.contractTemplate;
								}
							}
						}
					} catch (error) {
						console.log(error);
					}
					try {
						if (this.notEmpty(this.formData?.salesContract)) {
							let item = this.salesContractList.find(e => {
								return (
									e.id ==
									this.formData.salesContract
										.contractTemplateId
								);
							});

							this.salesContract = this._.cloneDeep(item);
						}
					} catch (error) {
						console.log(error);
					}

					try {
						if (this.notEmpty(this.formData.guaranteeContract)) {
							let item = this.guaranteeContractList.find(e => {
								return (
									e.id ==
									this.formData.guaranteeContract
										.contractTemplateId
								);
							});
							this.guaranteeContract = this._.cloneDeep(item);
						}
					} catch (error) {
						console.log(error);
					}
					this.$forceUpdate();
				});
			},
		},
	};
</script>

<style lang="scss" scoped>
	.box {
		margin: 20px;
		padding: 20px;
		border-radius: 8px;
		background-color: #fff;
		.title {
			font-size: 16px;
			font-family: PingFangSC, PingFang SC;
			font-weight: 500;
			color: #333333;
			line-height: 22px;
			padding-bottom: 15px;
			border-bottom: 1px solid #e9e9e9;
		}
	}
	.container_title {
		margin-bottom: 10px;
	}
	.config_box {
		display: grid;
		gap: 25px;
		grid-template-columns: repeat(3, minmax(300px, 1fr));
		margin-top: 10px;
		::v-deep .el-form-item {
			display: flex;
			flex-direction: column;
			padding: 16px;
			box-sizing: border-box;
			border-radius: 4px;
			border: 1px solid #dadada;
		}
		::v-deep .el-form-item__label {
			text-align: left;
			margin-bottom: 8px;
			width: 100% !important;
			font-size: 14px;
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			color: #464646;
			line-height: 22px;
			display: flex;
		}
		::v-deep .el-form-item__content {
			margin-top: 20px;
			margin-left: 0 !important;
		}
		.config_box-label {
			flex: 1;
			display: flex;
			justify-content: space-between;
		}
		::v-deep .el-date-editor {
			width: 100%;
			max-width: 300px;
		}

		::v-deep .el-input {
			width: 100%;
			max-width: 300px;
		}
		::v-deep .el-select {
			width: 100%;
			max-width: 300px;
		}
		::v-deep .el-textarea {
			width: 100%;
			max-width: 300px;
		}
		::v-deep .el-radio-group {
			display: flex;
			flex-direction: column;
			gap: 10px;
		}
	}
	::v-deep .el-input-number {
		.el-input-number__decrease,
		.el-input-number__increase {
			display: none;
		}
		input {
			padding: 5px;
			text-align: left;
		}
	}
	.input-number {
		width: 60px;
	}
	.container_content_title {
		font-size: 14px;
		font-family: PingFangSC, PingFang SC;
		font-weight: 400;
		color: #464646;
	}
	.templateBox {
		::v-deep .el-form-item {
			display: flex;
			flex-direction: column;
			box-sizing: border-box;
		}
		::v-deep .el-form-item__label {
			text-align: left;
			margin-bottom: 8px;
			width: 100% !important;
			font-size: 14px;
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			color: #464646;
			line-height: 22px;
			display: flex;
		}
		::v-deep .el-form-item__content {
			margin-top: 10px;
			margin-left: 0 !important;
		}
	}
	.remake {
		::v-deep .el-form-item {
			display: flex;
			flex-direction: column;
			box-sizing: border-box;
		}
		::v-deep .el-form-item__label {
			text-align: left;
			margin-bottom: 8px;
			width: 100% !important;
			font-size: 14px;
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			color: #464646;
			line-height: 22px;
			display: flex;
		}
		::v-deep .el-form-item__content {
			margin-top: 10px;
			margin-left: 0 !important;
		}
	}
	.cspan2 {
		grid-row-start: span 2;
	}
	.span3 {
		grid-column-start: span 3;
	}
	.btn {
		cursor: pointer;
		display: flex;
		justify-content: center;
		align-items: center;
		height: 48px;
		background: #ffffff;
		border-radius: 4px;
		border: 1px solid #dadada;
		color: #1890ff;
		margin-top: 15px;
		font-size: 14px;
	}
</style>
